package com.himiotech.core.framework.config.init;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.himiotech.core.framework.config.HimioConfig;
import com.himiotech.core.framework.helper.constant.Constants;
import com.himiotech.core.framework.helper.utils.CacheUtils;
import com.himiotech.core.project.data.mapper.DictDataMapper;
import com.himiotech.core.project.helper.exception.TaskException;
import com.himiotech.core.project.helper.utils.DictUtils;
import com.himiotech.core.project.helper.utils.job.ScheduleUtils;
import com.himiotech.core.project.model.entity.Config;
import com.himiotech.core.project.model.entity.dict.DictData;
import com.himiotech.core.project.model.entity.dict.DictType;
import com.himiotech.core.project.model.entity.job.Job;
import com.himiotech.core.project.service.IConfigService;
import com.himiotech.core.project.service.IDictTypeService;
import com.himiotech.core.project.service.IJobService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

/**
 * 初始化事件监听器
 * 由于之前很多实用的@PostConstruct，导致自动执行sql还未执行就查询数据库
 * 导致失败（table not exist)所以需要执行完毕之后再去初始化相关缓存数据
 *
 * @author wuwenbin
 **/
@Slf4j
@Component
public class HimioAppInitListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private IConfigService configService;
    @Autowired
    private IDictTypeService dictTypeService;
    @Autowired
    private DictDataMapper dictDataMapper;
    @Autowired
    private Scheduler scheduler;
    @Autowired
    private IJobService jobService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //初始化缓存
        log.info("==> 初始化系统配置缓存，请稍后...");
        initSysConfigCache();
        log.info("<==  完成。");
        log.info("==> 初始化系统字典缓存，请稍后...");
        initSysDictCache();
        log.info("<== 完成。");
        log.info("==> 初始化任务定时器，请稍后...");
        try {
            initSysJob();
        } catch (SchedulerException e) {
            e.printStackTrace();
        } catch (TaskException e) {
            e.printStackTrace();
            System.exit(0);
        }
        log.info("==> 初始化上传文件目录，请稍候...");
        initSysUploadDir();
        log.info("<== 完成。");
    }

    private void initSysUploadDir() {
        String uploadPath = HimioConfig.getUploadPath();
        File file = new File(uploadPath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 项目启动时，初始化参数到缓存
     */
    public void initSysConfigCache() {
        configService.loadingConfigCache();
    }

    /**
     * 项目启动时，初始化字典到缓存
     */
    public void initSysDictCache() {
        dictTypeService.loadingDictCache();
        List<DictType> dictTypeList = dictTypeService.list();
        for (DictType dictType : dictTypeList) {
            List<DictData> dictDataList = dictDataMapper.selectDictDataByType(dictType.getDictType());
            DictUtils.setDictCache(dictType.getDictType(), dictDataList);
        }
    }

    /**
     * 项目启动时，初始化定时器
     * 主要是防止手动修改数据库导致未同步到定时任务处理（注：不能手动修改数据库ID和任务组名，否则会导致脏数据）
     */
    public void initSysJob() throws SchedulerException, TaskException {
        scheduler.clear();
        List<Job> jobList = jobService.list();
        for (Job job : jobList) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }

}
